#include <bits/stdc++.h>

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

void printf_list(ListNode *head)
{
    ListNode *cur = head;
    while (cur != nullptr)
    {
        printf("%d ", cur->val);
        cur = cur->next;
    }
    printf("\n");
}

class Solution
{
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
    {
        int length_a = 0;
        ListNode *cur_a = headA;
        while (cur_a != nullptr)
        {
            length_a++;
            cur_a = cur_a->next;
        }
        cur_a = headA;
        int length_b = 0;
        ListNode *cur_b = headB;
        while (cur_b != nullptr)
        {
            length_b++;
            cur_b = cur_b->next;
        }
        cur_b = headB;
        //printf("%d\n", length_a);
        //printf("%d\n", length_b);
        if (length_a > length_b)
        {
            int count = length_a - length_b;
            while (count != 0)
            {
                count--;
                cur_a = cur_a->next;
            }
        }
        else
        {
            int count = length_b - length_a;
            while (count != 0)
            {
                count--;
                cur_b = cur_b->next;
            }
        }
        while (cur_a != cur_b)
        {
            cur_a = cur_a->next;
            cur_b = cur_b->next;
        }
        return cur_a;
    }
};

int main()
{
    ListNode *head1 = new ListNode(4);
    ListNode *node1 = new ListNode(1);
    ListNode *node2 = new ListNode(8);
    ListNode *node3 = new ListNode(4);
    ListNode *node4 = new ListNode(5);

    head1->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = node4;

    printf_list(head1);

    ListNode *head2 = new ListNode(5);
    ListNode *node2_1 = new ListNode(0);
    ListNode *node2_2 = new ListNode(1);

    head2->next = node2_1;
    node2_1->next = node2_2;
    node2_2->next = node2;

    printf_list(head2);

    Solution sol;
    ListNode *intersection_head = sol.getIntersectionNode(head1, head2);

    printf_list(intersection_head);

    return 0;
}
